import { Flex, Input, message, Modal, Spin } from "antd";

import { useState, useEffect } from "react";
import { AddConnection } from "./Connection";
import {
  DeleteConnection,
  ListConnections,
} from "../../wailsjs/go/services/ConnectionService";
import { types } from "../../wailsjs/go/models";
import { DeleteFilled } from "@ant-design/icons";

const ListConnection = () => {
  const [connections, setConnections] = useState<types.Connection[]>([]);
  const [loading, setLoading] = useState(false);
  const [refreshConnects, setRefreshConnections] = useState(false);

  useEffect(() => {
    setLoading(true);
    ListConnections()
      .then((res: types.JSResp) => {
        if (res.success && Array.isArray(res.data)) {
          setConnections(res.data);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  }, [refreshConnects]);

  const onDelete = (connection: types.Connection) => {
    Modal.confirm({
      title: "删除连接",
      content: "确定要删除该连接吗？",
      destroyOnClose: true,
      onOk: () => {
        DeleteConnection(connection.uuid).then((res) => {
          if (res.success) {
            setRefreshConnections(!refreshConnects);
          } else {
            message.error(res.msg);
          }
        });
      },
    });
  };

  return (
    <Spin spinning={loading}>
      {connections.map((value) => {
        return (
          <div key={value.uuid}>
            <Flex justify="space-between">
              <div>{value.name}</div>
              <DeleteFilled
                title="删除"
                style={{ color: "red" }}
                onClick={() => onDelete(value)}
              />
            </Flex>
          </div>
        );
      })}
    </Spin>
  );
};

const Databases = () => {
  const [searchValue, setSearchValue] = useState("");

  const onSearch = (value: string) => {
    setSearchValue(value);
  };

  return (
    <>
      <Flex gap="small">
        <Input.Search
          placeholder="搜索配置"
          allowClear
          onSearch={onSearch}
          style={{ width: "300px", flex: 1 }}
        />
        <AddConnection />
      </Flex>
      <ListConnection />
    </>
  );
};

export default Databases;
